package com.cmf.myproject.filter;

import java.io.IOException;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.stereotype.Component;

@Component
@ServletComponentScan
public class RequestLogFilter implements Filter {
	protected final Logger logger = LoggerFactory.getLogger(getClass());
	
	@Override
	public void destroy() {
		
	}
	
	
	private static final String[] urls = { "/components", "/favicon.ico","/boss/assets/img","/api","/swagger-resources","/v2/api-docs","/webjars","/swagger-ui.html","/druid" };
	
	@Override
	public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain chain)
																						throws IOException,
																						ServletException {
		HttpServletRequest request = (HttpServletRequest) arg0;
		HttpServletResponse response = (HttpServletResponse) arg1;
		response.setHeader("Access-Control-Allow-Origin", "*");
		response.setHeader("Access-Control-Allow-Methods", "POST,OPTIONS,GET");
		response.setHeader("Access-Control-Allow-Headers", "Content-Type,XFILENAME,XFILECATEGORY,XFILESIZE");

		String uri = request.getRequestURI();
		boolean ignore =false;
		for(String url:urls){
			if(uri.startsWith(url)){
				ignore = true;
				break;
			}
		}

		if(!ignore){
			StringBuilder stringBuilder = new StringBuilder("HTTP ["+request.getMethod()+"]请求URI：" + uri + "; ");
			boolean findparam =false;
			int i = 0;
			Map<String,String[]> paramMap = request.getParameterMap();
			for(String param:paramMap.keySet()){
				findparam = true;
				if(i == 0) {
					stringBuilder.append("[");
				}
				stringBuilder.append(param+":");
				String[] values = request.getParameterValues(param);
				for(String value:values){
					stringBuilder.append(StringUtils.isBlank(value)?"null":value+" ");
				}
				if(i < paramMap.size()-1) {
					stringBuilder.append("，");
				}
				else {
					stringBuilder.append("]");
				}
				i++;
			}
			if(!findparam){
				stringBuilder.append("[无参数传入]");
			}
			logger.info(stringBuilder.toString().replaceAll("_dc:[0-9]*\\s*，{1}", ""));
		}
		chain.doFilter(request, response);
	}
	
	@Override
	public void init(FilterConfig config) throws ServletException {
		
	}
}
